﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using LitJson;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System;
public class CSH : MonoBehaviour 
{
	private string ServerIp="192.168.197.72";
	private int Port=22222;
	private Socket cs;
	private Queue<string> msg;
	public static CSH instance;
	// Use this for initialization
	void Awake()
	{
		msg=new Queue<string>();
		instance=this;
	}
	
	// Update is called once per frame
	void Update () 
	{
		
	}
	Socket GetClientSocket(out string NewServerIp)
	{
		NewServerIp=ServerIp;
		AddressFamily  IpType= AddressFamily.InterNetwork;
		try
		{
			//string mIPv6 =SdkToU3d.GetIPv6(ServerIp, Port.ToString());
			string mIPv6="";
			print("My Ip Address Is:"+mIPv6);
			if (!string.IsNullOrEmpty(mIPv6))
			{
				string[] m_StrTemp = System.Text.RegularExpressions.Regex.Split(mIPv6, "&&");
				if (m_StrTemp != null && m_StrTemp.Length >= 2)
				{
					string mIPType = m_StrTemp[1];
					if (mIPType == "ipv6")
					{
						NewServerIp = m_StrTemp[0];
						IpType = AddressFamily.InterNetworkV6;
					}
					else if(mIPType == "ipv4")
					{
						NewServerIp=m_StrTemp[0];
					}
				}
			}
		}
		catch (Exception e)
		{

		}
		Socket _ClientSocket= new Socket(IpType, SocketType.Stream, ProtocolType.Tcp);
		return _ClientSocket;
	}
	void ConnectToServer()
	{
		string NewServerIp=ServerIp;
		cs=GetClientSocket(out NewServerIp);
		cs.BeginConnect(new IPEndPoint(IPAddress.Parse(NewServerIp),Port),OnConnect,null);
	}
	void OnConnect(IAsyncResult ir)
	{
		byte[] buffer=new byte[1024*16];
		cs.BeginReceive(buffer,0,buffer.Length,SocketFlags.None,OnRecieveMsg,buffer);
	}
	void OnRecieveMsg(IAsyncResult ir)
	{
		int length=cs.EndReceive(ir);
		byte[] OrigBuffer=(byte[])ir.AsyncState;
		byte[] NewBuffer=new byte[length];
		for(int i=0;i<length;i++)
		{
			NewBuffer[i]=OrigBuffer[i];
		}
		msg.Enqueue(Encoding.UTF8.GetString(NewBuffer));
		cs.BeginReceive(OrigBuffer,0,OrigBuffer.Length,SocketFlags.None,OnRecieveMsg,OrigBuffer);
	}
	void OnApplicationQuit()
	{
		cs.Close();
	}
	void OnApplicationPause(bool IsPause)
	{
		if(IsPause)//游戏暂停
		{
			print("Game Paused");

		}
		else//游戏继续
		{

			print("Game Continued");
		}
	}
	public void SendData(object obj)//向服务器发请求
	{


	}
	JsonData ConstructReqData(object obj)//构造请求数据
	{
		JsonData jd=new JsonData();
		jd["type"]=0;
		jd["msg"]=1;
		return jd;
	}
	public void HandleData()//处理服务器响应
	{
		while(msg.Count>0)
		{
			string s=msg.Dequeue();
			JsonData jd=JsonMapper.ToObject(s);
		}

	}
}
